<?php

namespace App\Http\Controllers;

use App\Models\SafePlanBanner;
use Illuminate\Http\Request;

class SafePlanBannerController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->get('perPage', 10);
        $query = SafePlanBanner::query();
        $info = $query->paginate($perPage)->toArray();

        return $this->returnJSON([
            'count' => $info['total'],
            'rows' => $info['data']
        ]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'photo' => 'required|max:255',
            'href' => 'max:1024',
        ]);

        $node = new SafePlanBanner();
        $data = $request->only([
            'photo',
            'href',
            'jump_mode'
        ]);

        $data['status'] = 1;
        $data['title'] = '';
        $data['jump_mode'] = intval($data['jump_mode']) || 0;
        $data['sort'] = 0;

        $node->fill($data);

        if ($node->save()) {
            return $this->returnJSON(null, 0, '新增成功');
        }
        return $this->returnJSON(null, 500, '新建失败');
    }

    public function update(Request $request, $id) {
        $node = SafePlanBanner::findOrFail($id);

        $this->validate($request, [
            'photo' => 'required|max:255',
            'href' => 'max:1024',
        ]);

        $data = $request->only([
            'photo',
            'href',
            'jump_mode'
        ]);

        $node->fill($data);
        if ($node->save()) {
            return $this->returnJSON(null, 0, '保存成功');
        }
        return $this->returnJSON(null, 500, '保存失败');
    }

    public function destroy(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));

        if (SafePlanBanner::whereIn('id', $ids)->delete()) {
            return $this->returnJSON($ids, 0, '删除成功');
        } else {
            return $this->returnJSON(null, 1, "删除失败");
        }
    }

    public function online(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = SafePlanBanner::whereIn('id',  $ids)->update(['status' => 1]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '启用成功');
        } else {
            return $this->returnJSON(null, 1, "启用失败");
        }
    }
    public function offline(Request $request, $id)
    {
        $ids = array_map(function($item) {
            return intval($item);
        }, explode(",", $id));
        $result = SafePlanBanner::whereIn('id',  $ids)->update(['status' => 0]);
//    Log::info(Post::where('id', $ids)->toSql());
        if ($result) {
            return $this->returnJSON($ids, 0, '禁用成功');
        } else {
            return $this->returnJSON(null, 1, "禁用失败");
        }
    }
}
